var tmpCheckline;
$(function () {

    $('#my-a-command').on('click', function () {
        $('#my-div-command').modal({
            relatedTarget: this,
            onConfirm: function (e) {
                console.log(e.data);
                $.post('/service/command', {
                    command: $.trim(e.data)
                }, function (d) {
                    if (d.code != "successful") $.msgg.message(d.message);
                });
            }
        });
    });

    $('#my-a-add').on('click', function () {
        $('#my-div-add').modal({
            relatedTarget: this,
            onConfirm: function (e) {
                console.log(e.data);
                if (confirm("确认提交吗")) {
                    $.post('/service/add', {
                        projectName: e.data[0],
                        url: e.data[1],
                        loginName: e.data[2],
                        loginPass: e.data[3],
                        checkoutPath: e.data[4],
                        tomcatHome: e.data[5],
                        command: e.data[6]
                    }, function (d) {
                        if (d.code != "successful") $.msgg.message(d.message);
                        else {
                            $.msgg.message(d.message);
                            // addhtml1(d.data);
                            window.location.reload();
                        }
                    });
                }
            },
            onCancel: function (e) {
            }
        });
    });

    $('#my-a-edit').bind('click', function () {
        var checked = $('input[type="checkbox"]:checked');
        if (checked.length == 0) {
            $.msgg.message("至少勾选一条");
            return;
        }
        $.post('/service/query', {n: checked.attr('title')}, function (d) {
            if (d.code != "successful") {
                $.msgg.message(d.message);
            } else {
                $('#my-input-project-name').val(d.data.projectName);
                $('#my-input-url').val(d.data.url);
                $('#my-input-login-name').val(d.data.loginName);
                $('#my-input-login-pass').val(d.data.loginPass);
                $('#my-input-checkout-path').val(d.data.checkoutPath);
                $('#my-input-tomcat-home').val(d.data.tomcatHome);
                $('#my-input-command').val(d.data.command);
            }
        });
        $('#my-div-add').modal({
            relatedTarget: this,
            onConfirm: function (e) {
                console.log(e.data);
                if (confirm("确认提交吗")) {
                    $.post('/service/add', {
                        projectName: e.data[0],
                        url: e.data[1],
                        loginName: e.data[2],
                        loginPass: e.data[3],
                        checkoutPath: e.data[4],
                        tomcatHome: e.data[5],
                        command: e.data[6]
                    }, function (d) {
                        if (d.code != "successful") $.msgg.message(d.message);
                        else {
                            $.msgg.message(d.message);
                            // addhtml1(d.data);
                            window.location.reload();
                        }
                    });
                }
            },
            onCancel: function (e) {
            }
        });
    });

    $('#my-a-bulid').bind('click', function () {
        // $('#my-modal-loading').modal();
        var checked = $('input[type="checkbox"]:checked');
        if (checked.length == 0) {
            $.msgg.message("至少勾选一条");
            return;
        }
        tmpCheckline = checked.parent().parent().parent().parent();//.find('td')[7];
        tmpCheckline = $(tmpCheckline);
        $('#my-a-bulid').hide();
        appendMsg('项目已开始编译请等待...');
        $.get('/service/build', {projectName: checked.attr('title')}, function (d) {
            // $('#my-modal-loading').modal('close');
            $.msgg.message(d.message);
            $('#my-a-bulid').show();
            checked.attr('checked', false);
        });
    });

    $('#my-a-del').bind('click', function () {
        var checkboxs = [];
        $('input[type="checkbox"]:checked').each(function (a, b) {
            checkboxs.push($(b).attr('title'));
        });
        if (checkboxs.length == 0) {
            $.msgg.message("勾选至少一条");
            return;
        }
        if (confirm("确认删除吗")) {
            $.ajax({
                url: '/service/delete',
                type: 'post',
                dataType: "JSON",//返回数据类型
                async: true,//使用同步的方式,true为异步方式
                contentType: 'application/json;charset=utf-8',
                data: JSON.stringify({names: checkboxs}),
                success: function (data) {
                    if (data.code == 'successful') {
                        for (var i = 0; i < checkboxs.length; i++) {
                            $($('input[title="' + checkboxs[i] + '"]').parent().parent().parent().parent()).remove();
                        }
                    } else {
                        $.msgg.message(data.message);
                    }
                },
                error: function (e) {
                    console.log(e);
                    if (e.status == 500) {
                        $.msgg.message("Error >>> " + e.responseJSON.message);
                    }
                }
            });
        }
    });

    $('#my-a-startup').bind('click', function () {
        var checked = $('input[type="checkbox"]:checked');
        if (checked.length == 0) {
            $.msgg.message("至少勾选一条");
            return;
        }
        $('#my-modal-loading').modal();
        $.post('/service/tomcat', {action: 'startup', projectName: checked.attr('title')}, function (d) {
            $('#my-modal-loading').modal('close');
            $.msgg.message(d.message);
        });
    });

    $('#my-a-stop').bind('click', function () {
        var checked = $('input[type="checkbox"]:checked');
        if (checked.length == 0) {
            $.msgg.message("至少勾选一条");
            return;
        }
        $('#my-modal-loading').modal();
        $.post('/service/tomcat', {action: 'stop', projectName: checked.attr('title')}, function (d) {
            $('#my-modal-loading').modal('close');
            $.msgg.message(d.message);
        });
    });

    $.get('/service/query', function (d) {
        if (d.code != 'successful') {
            $.msgg.message("获取数据异常");
        } else {
            $(d.data).each(function (a, b) {
                addhtml1(b);
            });
        }
    });
});

function addhtml1(b) {
    var html;
    if (b.status == 'successful') {
        html = '<tr class="am-success">'
    } else if (b.status == 'fail') {
        html = '<tr class="am-danger">'
    } else {
        html = '<tr class="am-warning">'
    }
    html += '' +
        '       <td class="">' +
        '           <div class="am-checkbox am-margin-0">' +
        '               <label>' +
        '                   <input type="checkbox" title="' + b.projectName + '" style="margin-top: 8px;"/>' +
        '               </label>' +
        '           </div>' +
        '       </td>' +
        '       <td>' + b.projectName + '&nbsp;&nbsp;[' + (b.buildCount == undefined || b.buildCount == null ? "0" : b.buildCount) + ']</td>' +
        '       <td>' + b.url + '</td>' +
        '       <td>' + b.loginName + '</td>' +
        '       <td>' + (b.checkoutPath == undefined || b.checkoutPath == null ? "N/A" : b.checkoutPath) + '</td>' +
        '       <td>' + (b.tomcatHome == undefined || b.tomcatHome == null ? "N/A" : b.tomcatHome) + '</td>' +
        '       <td>' + (b.buildTime == undefined || b.buildTime == null ? "N/A" : formatDateTime(b.buildTime)) + '</td>' +
        '       <td>' + b.status + '</td>' +
        '   </tr>';
    $('#my-tbody').append(html)
}

function formatDateTime(timeStamp) {
    var date = new Date();
    date.setTime(timeStamp);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
}

var ws;
$(function () {
    var basePath = $('#basePath').text();
    if ('WebSocket' in window) {
        ws = new WebSocket('ws://' + basePath + '/ws/substart/' + getUuid())
    } else if ('MozWebSocket' in window) {
        ws = new MozWebSocket('ws://' + basePath + '/ws/substart/' + getUuid());
    } else {
        alert('浏览器不支持 wesocket!');
    }

    ws.onmessage = function (e) {
        if (e.data == 'successful') {
            // $('#my-a-bulid').show();
            tmpCheckline.removeClass("am-warning");
            tmpCheckline.removeClass("am-danger");
            tmpCheckline.addClass("am-success");
        } else if (e.data == 'fail') {
            // $('#my-a-bulid').show();
            tmpCheckline.removeClass("am-warning");
            tmpCheckline.removeClass("am-success");
            tmpCheckline.addClass("am-danger");
        } else {
            appendMsg(e.data); //来自服务器的消息
            // $('#my-a-bulid').hide();
        }
    };
    ws.onclose = function (e) {
        appendMsg('与服务器连接中断');
    };
    ws.onopen = function (e) {
        appendMsg('已连接服务器');
    };
    // $('button').bind('click', function () {
    //     ws.send($('#input-msg').val());
    // });
});

function appendMsg(msg) {
    $('#build-msg').append('<div>' + msg + '</div>')
    $(window).scrollTop($(document).height());
}

function getIp() {
    var ip = getUuid();
    $.ajax({
        url: '/service/ip',
        type: 'get',
        dataType: "JSON",//返回数据类型
        async: false,//使用同步的方式,true为异步方式
        // contentType: 'application/json;charset=utf-8',
        // data: JSON.stringify({names: checkboxs}),
        success: function (data) {
            if (data.code == 'successful') {
                ip = data.message;
            } else {
                $.msgg.message(data.message);
            }
        },
        error: function (e) {
            console.log(e);
            if (e.status == 500) {
                $.msgg.message(e.responseJSON.message);
            }
        }
    });
    return ip;
}

function getUuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "";
    var uuid = s.join("");
    console.log(uuid);
    return uuid;
}

function cleanLog(obj) {
    var p = $(obj).parent();
    p.text('');
    p.append('<div style="color:red;font-size: 16px;">日志：</div>[<a href="javascript:;" style="color: blue;" onclick="cleanLog(this)">Clean</a>]')
}
